//
//  ConditionSelectViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/12/18.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit

protocol SearchCondition {
    
    func search(with orgcode: String?,year: Int?,projname: String?)->Void
    
    func search(with orgcode: String?,yearmonth: String?,projname: String?)->Void
    
    func reset()->Void
}

class ConditionSelectViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {
    
    var delegate: SearchCondition?
    
    var ifdepart = false
    
    let yearPicker = YearPicker.init(frame: CGRect.init(origin: .zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    
    let yearField = UITextField()
    
    var _year: Int = -1
    var year: Int {
        get{
            return _year
        }
        set{
            _year = newValue
        }
    }
    
    var projectname = ""
    
    @objc override func dismiss()->Void{
        self.view.isUserInteractionEnabled = false
        let animation = POPSpringAnimation.init(propertyNamed: kPOPViewFrame)
        animation?.beginTime = CACurrentMediaTime()
        animation?.toValue = NSValue.init(cgRect: CGRect.init(origin: CGPoint.init(x: 0, y: -220), size: CGSize(width: self.view.width, height: 220)))
        animation?.springSpeed = 50
        animation?.springBounciness = 5
        func complete(animation: POPAnimation?,complete: Bool)->Void{
            super.dismiss()
        }
        animation?.completionBlock = complete
        self.tableView.pop_add(animation, forKey: "t")
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.projectname = textField.text ?? ""
    }
    
    override func endedit() {
        super.endedit()
        let cell = tableView.cellForRow(at: IndexPath.init(row: 1, section: 0))
        cell?.detailTextLabel?.text = String(yearPicker.selectedYear)
    }
    
    let tableView = UITableView.init(frame: .zero, style: .plain)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.isScrollEnabled = false
        self.view.addSubview(self.tableView)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        yearPicker.years = (2018 ..< 2118).map({ (result) -> Int in
            return result
        })
        
        if let index = self.yearPicker.years.firstIndex(of: self.year) {
            if self.yearPicker.years.count > index {
                self.yearPicker.datePicker.selectRow(index, inComponent: 0, animated: false)
            }
        }
        
        self.tableView.register(UINib.init(nibName: "ProjectInputTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "ProjectInputTableViewCell")
        self.view.addSubview(yearField)
        yearField.inputAccessoryView = self.toolbarview
        yearField.inputView = yearPicker
        let footer = UIView()
        footer.backgroundColor = UIColor.white
        footer.frame = CGRect.init(origin: CGPoint.zero, size: CGSize(width: self.view.width, height: 55))
        let separator = UIView()
        separator.frame = CGRect.init(x: 15, y: 0, width: self.view.width, height: 0.5)
        separator.backgroundColor = self.tableView.separatorColor
        footer.addSubview(separator)
        let stack = UIStackView()
        footer.addSubview(stack)
        stack.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalToSuperview()
        }
        stack.axis = .horizontal
        stack.alignment = .fill
        stack.distribution = .fillEqually
        
        let reset = UIButton.init(type: .system)
        reset.setTitle("重置", for: .normal)
        reset.setTitleColor(UIColor.hex("999999"), for: .normal)
        reset.addTarget(self, action: #selector(resetAction), for: .touchUpInside)
        stack.addArrangedSubview(reset)
        
        let search = UIButton.init(type: .system)
        search.setTitleColor(UIColor.white, for: .normal)
        search.backgroundColor = UIColor.hex("2B89DF")
        search.setTitle("搜索", for: .normal)
        search.addTarget(self, action: #selector(searchAction), for: .touchUpInside)
        stack.addArrangedSubview(search)
        self.tableView.tableFooterView = footer
        self.tableView.top = -220
        self.tableView.left = 0
        self.tableView.width = self.view.width
        self.tableView.height = 220
    }
    
    func animator()->Void{
        let animation = POPBasicAnimation.init(propertyNamed: kPOPViewFrame)
        animation?.beginTime = CACurrentMediaTime()
        animation?.fromValue = NSValue.init(cgRect: self.tableView.frame)
        animation?.toValue = NSValue.init(cgRect: CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize(width: self.view.width, height: 220)))
        animation?.duration = TimeInterval.init(0.25)
        self.tableView.pop_add(animation, forKey: "t")
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.animator()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if ifdepart == true {
            return 2
        } else {
            return 3
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 2 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProjectInputTableViewCell") as! ProjectInputTableViewCell
            cell.contentLabel.delegate = self
            return cell
        } else {
            var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
            if cell == nil {
                cell = UITableViewCell.init(style: .value1, reuseIdentifier: "UITableViewCell")
                cell?.selectionStyle = .none
                cell?.textLabel?.font = UIFont.systemFont(ofSize: 17)
                cell?.detailTextLabel?.font = UIFont.systemFont(ofSize: 14)
                cell?.accessoryType = .disclosureIndicator
            }
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            let targetitem = self.companys.filter { (json) -> Bool in
                return json.contents?["code"]?.rawString() == self.selectedOrg
            }
            cell.textLabel?.text = "部门:"
            if targetitem.count > 0 {
                let item = targetitem[0]
                cell.detailTextLabel?.text = item.contents?["name"]?.rawString()
            }
        } else if indexPath.row == 1 {
            cell.textLabel?.text = "年份:"
            if year > -1 {
                cell.detailTextLabel?.text = String(year)
            }
        } else if indexPath.row == 2 {
            if let cel = cell as? ProjectInputTableViewCell {
                cel.contentLabel.text = self.projectname
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.row == 0 {
            self.popalert()
        } else if indexPath.row == 1 {
            self.yearField.becomeFirstResponder()
        }
    }
    
    var companys: [JSON] = []
    var selectedOrg = ""
    @objc func popalert() -> Void {
        
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                self.selectedOrg = item.contents?["code"]?.rawString() ?? ""
                let cell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 0))
                cell?.detailTextLabel?.text = item.contents?["name"]?.rawString()
            }
            alert.addAction(sheet)
        }
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    @objc func searchAction()->Void{
        self.view.endEditing(true)
        let cell = self.tableView.cellForRow(at: IndexPath.init(row: 2, section: 0)) as! ProjectInputTableViewCell
        let yearcell = self.tableView.cellForRow(at: IndexPath.init(row: 1, section: 0))
        if (yearcell?.detailTextLabel?.text?.count ?? 0) > 0 {
            self.delegate?.search(with: self.selectedOrg, year: self.yearPicker.selectedYear, projname: cell.contentLabel.text)
        } else {
            self.delegate?.search(with: self.selectedOrg, year: nil, projname: cell.contentLabel.text)
        }
        self.dismiss()
    }
    
    @objc func resetAction()->Void{
        self.delegate?.reset()
        self.dismiss()
    }

    override func reset() {
        self.delegate?.reset()
        self.dismiss()
    }
    
}
